// pages/rightsMgt/index.js
import Common from '../../common/common.js';
let common = new Common;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    authOpe:false,
    //搜索用-关键字
    keyValue: "",
    //选中的权限标签页
    uuid: '',
    //店主和店长
    managerList: [],
    //权限列表
    authList: [],
    //员工列表
    userListAll: [],
    //上拉加载控制
    scrollHeight: 0,
    isLoading: false,
    hasData: true,
    pageNum: 1,
    pageSize: 100,
    //是否已全选
    checkedAll: false
  },
  // 详情
  toDetil:function(){
    let routeUrl = '/pages/rightsMgt/customerInfo/customerInfo';
    let routeType = 'navigateTo';
    let params = '';
    common.routeLink(routeUrl, params, routeType)
  },
  /**
   * 搜索控制
   */
  inputTyping: function (e) {
    this.setData({
      keyValue: e.detail.value
    });
    this.resetDatas();
    this.getUserList();
  },
  /**
   * 点击权限标签页
   */
  switchAuth: function(e){
    var that = this;
    console.log(e, typeof (e), typeof e === 'string', typeof (e) === 'string');
    //设置当前选中的权限ID
    var uuid = "";
    if (typeof (e) === 'string'){
      uuid = e;
    } else {
      uuid = e.currentTarget.dataset.uuid;
    }
    this.setData({
      uuid: uuid
    })
    //勾选有该权限的员工
    var that = this;
    var userListAll = that.data.userListAll;
    for (var i = 0; i < userListAll.length; i++) {
      var authorityList = userListAll[i].authorityList;
      var hasMatch = false;
      for (var j = 0; j < authorityList.length; j++) {
        if (uuid == authorityList[j].uuid) {
          userListAll[i].checked = true;
          hasMatch = true;
          break;
        }
      }
      if (!hasMatch) {
        userListAll[i].checked = false;
      }
    }
    that.setData({
      userListAll: userListAll
    })
  },
  /**
   * 查询店长和店主
   */
  getManagerList: function () {
    var data = {
      "orgSeq": getApp().globalData.orgSeq
    };
    common.requestAjax('/api/user-service/v1/user/queryMananger', 'POST', data).then(res => {
      if (res.data.code == 1) {
        this.setData({
          managerList: res.data.records
        })
      } else {
        common.showToast(res.data.message);
      }
    }).catch(err => {
      common.showToast(err);
    })
  },
  /**
   * 查询权限列表
   */
  getAuthList: function () {
    var data = {
      "orgSeq": getApp().globalData.orgSeq
    };
    common.requestAjax('/api/user-service/v1/detail/queryAuthority', 'POST', data).then(res => {
      if (res.data.code == 1) {
        this.setData({
          authList: res.data.records
        })
      } else {
        common.showToast(res.data.message);
      }
    }).catch(err => {
      console.log(err);
    })
  },
  /**
   * 查询用户列表
   */
  getUserList: function() {
    var that = this;
    var data = {
      "size": that.data.pageSize,
      "current": that.data.pageNum,
      "condition": {
        "orgSeq": getApp().globalData.orgSeq,
        "userName": that.data.keyValue
      }
    };
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    common.requestAjax('/api/user-service/v1/user/queryUsersById', 'POST', data).then(res => {
      // wx.hideLoading();
      if (res.data.code == 1) {
        var userList = res.data.records;
        var userListAll = that.data.userListAll;
        userListAll = userListAll.concat(userList);
        that.setData({
          userListAll: userListAll
        })
        //勾选有该权限的员工
        if(that.data.uuid != ''){
          that.switchAuth(that.data.uuid);
        }
      } else {
        wx.hideLoading();
        common.showToast(res.data.message);
      }
      //上拉加载控制
      if (res.data.records == null || res.data.records.length == 0) {
        that.errorDatas();
      } else {
        that.successDatas();
      }
    }).catch(err => {
      // wx.hideLoading();
      that.errorDatas();
      console.log(err);
    })
  },
  /**
   * 上拉加载重置数据
   */
  resetDatas: function () {
    //标识设置加载完成，页数+1，数据清空
    this.setData({
      isLoading: false,
      pageNum: 1,
      userListAll: []
    })
    //隐藏导航栏loading
    wx.hideNavigationBarLoading();
  },
  /**
   * 上拉加载成功处理
   */
  successDatas: function () {
    var that = this;
    //标识设置加载完成，页数+1
    that.setData({
      isLoading: false,
      pageNum: that.data.pageNum + 1
    })
    //隐藏导航栏loading
    wx.hideNavigationBarLoading();
    //隐藏暂无数据
    that.setData({
      hasData: true
    })
  },
  /**
   * 上拉加载失败处理
   */
  errorDatas: function () {
    var that = this;
    //标识设置加载完成
    that.setData({
      isLoading: false
    })
    //隐藏导航栏loading
    wx.hideNavigationBarLoading();
    //显示暂无数据
    if (that.data.pageNum == 1) {
      that.setData({
        hasData: false
      })
    }
  },
  /**
   * 上拉加载事件
   */
  scrollTolower(e) {
    var that = this;
    //正在加载中阻止再次查询
    if (that.data.isLoading) {
      return;
    }
    //显示导航栏loading
    wx.showNavigationBarLoading();
    //设置标识加载中
    that.setData({
      isLoading: true
    })
    //获取数据
    that.getUserList();
  },
  /**
   * 选择员工
   */
  checkboxChange: function (e) {
    var userId = e.currentTarget.dataset.userid;
    var valueArray = e.detail.value;
    var checked = false;
    if (valueArray[0] == userId) {
      //每个员工一个checkboxgroup，如果data-goodsid值和checkbox返回的值相等，表示选中商品
      checked = true;
    }
    var userListAll = this.data.userListAll;
    for (var i = 0; i < userListAll.length; i++) {
      if (userListAll[i].userId == userId) {
        userListAll[i].checked = checked;
        break;
      }
    }
    this.setData({
      userListAll: userListAll
    })
  },
  /**
   * 全选
   */
  checkboxChangeAll: function (e) {
    var checked = e.currentTarget.dataset.checkedall;
    checked = !Boolean(checked);
    var currentTab = this.data.currentTab;
    var userListAll = this.data.userListAll;
    for (var i = 0; i < userListAll.length; i++) {
      userListAll[i].checked = checked;
    }
    this.setData({
      userListAll: userListAll,
      checkedAll: checked
    })
  },
  /**
   * 获取已选择的员工列表
   */
  getChoosedUser: function () {
    var that = this;
    var data = [];
    var userListAll = that.data.userListAll;
    for (var j = 0; j < userListAll.length; j++) {
      var checked = userListAll[j].checked;
      if (checked) {
        data.push(
          userListAll[j].userId
        )
      }
    }
    return data;
  },
  /**
   * 设置权限
   */
  setAuth: function () {
    var userListAll = this.data.userListAll;
    var authList= this.data.authList;
    if(userListAll.length == 0){
      common.showToast("该店铺暂时没有员工");
      return;
    }
    if (authList.length == 0) {
      common.showToast("权限列表为空");
      return;
    }
    //点击第一个权限
    this.switchAuth(authList[0].uuid);
    this.setData({
      authOpe: true
    })
  },
  /**
   * 保存权限
   */
  saveAuth: function () {
    var that = this;
    var data = that.getChoosedUser();
    console.log(data);
    if (data.length == 0) {
      common.showToast("清选择员工");
      return;
    }
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    var dataWrap = {};
    dataWrap.orgSeq = getApp().globalData.orgSeq;
    dataWrap.authorityId = that.data.uuid;
    dataWrap.userList = data;
    common.requestAjax('/api/user-service/v1/detail/saveAuthority', 'POST', dataWrap).then(res => {
      wx.hideLoading();
      if (res.data.code == 1) {
        common.showToast(res.data.message);
        that.resetDatas();
        that.getUserList();
      } else {
        common.showToast(res.data.message);
      }
    }).catch(err => {
      wx.hideLoading();
      common.showToast("系统异常，请稍后重试！");
    })
  },
  /**
   * 取消权限
   */
  cancleAuth: function () {
    this.setData({
      authOpe: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // getApp().globalData.orgSeq = "2e8f4c46-ee3b-4b4b-9270-cf00c28271af";
    //获取店长和店主
    this.getManagerList();
    //获取权限列表
    this.getAuthList();
    //获取用户列表
    this.getUserList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //检测登陆状态
    // let loginStatus = wx.getStorageSync('loginStatus');
    // if (loginStatus == 0) {
    //   console.log('去登陆')
    //   //去授权登陆
    //   wx.navigateTo({
    //     url: '/pages/login/index',
    //   })
    // } else {

    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    //正在加载中阻止再次查询
    if (that.data.isLoading) {
      return;
    }
    //显示导航栏loading
    wx.showNavigationBarLoading();
    //设置标识加载中
    that.setData({
      isLoading: true
    })
    //获取数据
    that.resetDatas();
    that.getUserList();
    that.getAuthList();
    that.getManagerList();
    setTimeout(function(){
      wx.stopPullDownRefresh();
    }, 10)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})